//
//  UserAccountViewModel.m
//  weibo
//
//  Created by qiuming on 15/12/24.
//  Copyright © 2015年 qiuming. All rights reserved.
//

#import "UserAccountViewModel.h"
#import "UserAccountModel.h"
#import "MJExtension.h"

NSString *const userDataKey = @"userDataKey";

@implementation UserAccountViewModel
@synthesize userAccount = _userAccount;

#pragma mark - 用户帐户单例
+ (instancetype)sharedUserAccount {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
        [self loadUserData];
    }
    return self;
}

/// 是否登录
- (BOOL)isLogin {
    return ![self isExpired];
}

/// 返回用户头像地址
- (NSURL *)avatarUrl {
    return [NSURL URLWithString:_userAccount.avatar_large];
}

/// 加载用户信息
- (void)loadUserData {
    
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults]objectForKey:userDataKey];
    
    _userAccount = [UserAccountModel mj_objectWithKeyValues:dict];
    
    if ([self isExpired]) {
        _userAccount = nil;
    }
    DDLogInfo(@"启动时加载用户信息%@", _userAccount);
    
}

/// Token有效期
- (BOOL)isExpired {
    
    return ([_userAccount.expiresDate compare:[NSDate date]] != NSOrderedDescending);
}

#pragma mark - 发起网络请求通过code获取Token
- (void)accessTokenWithCode:(NSString *)code completed:(void (^)(BOOL))completed {
    
    NSAssert(completed != nil, @"一定要有回调");
    // 由code获取Token值
    [[NetworkTools sharedNetwordTool]accessTokenWithCode:code finish:^(id result, NSError *error) {
        
        if (error != nil) {
            completed(NO);
            return;
        }
        _userAccount = [UserAccountModel mj_objectWithKeyValues:result];
        
        [self loadUserInfoCompleted:completed];
        
    }];
}

#pragma mark - 由token值和UID获取用户信息
- (void)loadUserInfoCompleted:(void(^)(BOOL))completed {
    
    NSAssert(completed != nil, @"必须传入完成回调");
    
    [[NetworkTools sharedNetwordTool]loadUserWithUid:_userAccount.uid accessToken:_userAccount.access_token finish:^(id result, NSError *error) {
        
        if (error != nil) {
            completed(NO);
            return;
        }
        _userAccount.screen_name = result[@"screen_name"];
        _userAccount.avatar_large = result[@"avatar_large"];
        
        DDLogInfo(@"用户信息%@", result);
        
        [self saveUserData];
        
    }];
    
    
}

/// 保存用户信息
- (void)saveUserData {
    
    NSArray *key = @[@"screen_name", @"avatar_large", @"expiresDate", @"access_token", @"uid"];
    
    NSDictionary *dict = [_userAccount dictionaryWithValuesForKeys:key];
    
    [[NSUserDefaults standardUserDefaults]setObject:dict forKey:userDataKey];
    
    DDLogInfo(@"保存用户信息%@", dict);
}

@end
